package org.example.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.redis.RedisEmbeddingStore;
import lombok.extern.slf4j.Slf4j;
import org.example.result.Result;
import org.example.service.RedisVectorService;
import org.example.util.CreateModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class RedisVectorServiceImpl implements RedisVectorService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CreateModel createModel;

    @Override
    public Result<String> processAndStoreContent() {
        try {
            RedisEmbeddingStore redisEmbeddingStore = RedisEmbeddingStore.builder()
                    .host("127.0.0.1")
                    .port(6379)
                    .dimension(1536)
                    .build();

            // 获取所有匹配的键
            Set<String> keys = redisTemplate.keys("*");
            if (keys == null || keys.isEmpty()) {
                log.warn("No keys found in Redis");
                return Result.error("No keys found in Redis");
            }

            List<TextSegment> segments = new ArrayList<>();
            int successCount = 0;
            int errorCount = 0;

            // 处理每个键对应的内容
            for (String key : keys) {
                String jsonContent = redisTemplate.opsForValue().get(key);
                if (jsonContent != null) {
                    try {
                        // 打印原始内容以便调试
                        log.debug("Processing key: {}, Content: {}", key, jsonContent);
                        
                        // 尝试验证JSON格式
                        if (!isValidJson(jsonContent)) {
                            log.error("Invalid JSON format for key: {}", key);
                            errorCount++;
                            continue;
                        }

                        JSONObject jsonObject = JSON.parseObject(jsonContent);
                        String content = jsonObject.getString("content");
                        
                        if (content != null && !content.trim().isEmpty()) {
                            segments.add(TextSegment.from(content));
                            successCount++;
                        } else {
                            log.warn("Empty or null content for key: {}", key);
                            errorCount++;
                        }
                    } catch (JSONException e) {
                        log.error("JSON parsing error for key: " + key + ", Content: " + jsonContent, e);
                        errorCount++;
                    } catch (Exception e) {
                        log.error("Error processing content for key: " + key, e);
                        errorCount++;
                    }
                }
            }

            // 如果没有成功解析任何内容
            if (segments.isEmpty()) {
                log.error("No valid content found to process. Errors: {}", errorCount);
                return Result.error("No valid content found to process");
            }

            log.info("Successfully parsed {} segments, Failed to parse {} segments", successCount, errorCount);

            // 批量生成 embeddings 并存储
            int embeddingSuccessCount = 0;
            for (TextSegment segment : segments) {
                try {
                    Embedding embedding = createModel.createEmbeddingModel().embed(segment).content();
                    redisEmbeddingStore.add(embedding, segment);
                    embeddingSuccessCount++;
                } catch (Exception e) {
                    log.error("Error generating or storing embedding for segment: {}", segment.text(), e);
                }
            }

            if (embeddingSuccessCount > 0) {
                return Result.success(String.format("Successfully processed %d segments", embeddingSuccessCount));
            } else {
                return Result.error("Failed to process any segments");
            }

        } catch (Exception e) {
            log.error("Error in processAndStoreContent", e);
            return Result.error("Internal error: " + e.getMessage());
        }
    }

    private boolean isValidJson(String jsonContent) {
        try {
            JSON.parse(jsonContent);
            return true;
        } catch (JSONException e) {
            return false;
        }
    }
}